const { basename } = require("path")
const FormData = require("form-data")
const fs = require("fs")
const service = require("../../service/upload")

class Upload {
  constructor() {
    this.instance = null
  }
  static get Instance() {
    return this.instance || (this.instance = new Upload())
  }

  async upload(ctx) {
    const { file } = ctx.request.files
    if (!file) ctx.throw(404, "without field of file!")
    const localPath = file.path || ""
    const baseName = basename(localPath)
    ctx.rest({
      url: `${ctx.origin}/uploads/${baseName}`
    })
  }

  async uploadOSS(ctx) {
    const { file } = ctx.request.files
    if (!file) return ctx.throw(404, "Invalid data of 'file'!")
    const fd = new FormData()
    fd.append("smfile", fs.createReadStream(file.path))
    const headers = fd.getHeaders()
    headers.Authorization = `Basic ${process.env.OSS_SECRET}`
    headers["Content-Type"] = "multipart/form-data"
    const res = await service.upload(fd, { headers })
    // console.log(32323, res)
    if (!res.success) return ctx.throw(404, res.message)
    return ctx.rest(res)
  }
}

const I = Upload.Instance
module.exports = I
